<template>
  <div v-if="!canViewPage()" style="text-align: center; padding: 50px;">
    <a-result
      status="403"
      title="403"
      sub-title="抱歉，您没有权限访问用户角色管理页面。"
    >
      <template #extra>
        <a-button type="primary" @click="goToHome">返回首页</a-button>
      </template>
    </a-result>
  </div>
  
  <div v-else>
    <div style="margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center;">
      <div></div>
      <a-button 
        v-if="canAssign()" 
        type="primary" 
        @click="showModal"
      >
        分配角色
      </a-button>
    </div>

    <a-modal v-model:open="open" title="分配角色" @ok="handleAssignRole" @cancel="resetForm">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-item label="选择用户" name="userId">
          <a-select
            v-model:value="formState.userId"
            placeholder="请选择用户"
            show-search
            :filter-option="filterUserOption"
          >
            <a-select-option v-for="user in users" :key="user.id" :value="user.id">
              {{ user.username }} - {{ user.realName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择角色" name="roleIds">
          <a-select
            v-model:value="formState.roleIds"
            placeholder="请选择角色"
            mode="multiple"
            show-search
            :filter-option="filterRoleOption"
          >
            <a-select-option v-for="role in roles" :key="role.id" :value="role.id">
              {{ role.roleName }} ({{ role.roleCode }})
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <a-table 
      bordered
      :data-source="dataSource"
      :columns="columns"
      :loading="loading"
      :pagination="false"
      row-key="id"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column.dataIndex === 'username' || column.dataIndex === 'realName'">
          <div>
            <span>{{ text }}</span>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'roles'">
          <div>
            <template v-if="record.roles && record.roles.length > 0">
              <a-tag
                v-for="role in record.roles"
                :key="role.id"
                :color="getRoleColor(role.id)"
                style="margin: 2px"
              >
                {{ getRoleDisplayName(role) }}
              </a-tag>
            </template>
            <template v-else>
              <a-tag color="green">普通用户</a-tag>
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'createdAt'">
          {{ formatDate(text) }}
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <span>
            <a-button 
              v-if="canAssign()" 
              type="link" 
              size="small" 
              @click="showEditModal(record)"
              style="margin-right: 8px"
            >
              编辑角色
            </a-button>
            <a-popconfirm
              v-if="canAssign() && dataSource.length"
              title="确定要删除该用户的所有角色吗？"
              @confirm="onDeleteUserRoles(record.id)"
            >
              <a-button type="link" size="small" danger>删除角色</a-button>
            </a-popconfirm>
          </span>
        </template>
      </template>
    </a-table>
    
    <div style="margin-top: 16px; text-align: right;">
      <a-pagination 
        v-model:current="current"
        show-quick-jumper
        :page-size-options="['5', '10', '20']"
        :total="total"
        @change="onChange"
        :page-size="pageSize"
        show-size-changer
      />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import request from '@/utils/request'
import PermissionUtil from '@/utils/permission'

// 权限检查
const hasPermission = (permission) => PermissionUtil.hasPermission(permission)

// 页面查看：拥有 user:search 或 role:assign 或 role:manage 任一即可
const canViewPage = () => hasPermission('user:search') || hasPermission('role:assign') || hasPermission('role:manage')
// 分配/删除：需要 role:assign 或 role:manage
const canAssign = () => hasPermission('role:assign') || hasPermission('role:manage')

const originalDataSource = ref([])

// 分页
const current = ref(1)
const total = ref(0)
const pageSize = ref(10)
const loading = ref(false)

// 表单配置
const formRef = ref()
const labelCol = { span: 6 }
const wrapperCol = { span: 16 }
const open = ref(false)

const formState = reactive({
  userId: undefined,
  roleIds: []
})

const rules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

const users = ref([])
const roles = ref([])
const currentUser = ref(null)

const columns = [
  {
    title: '用户ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username'
  },
  {
    title: '真实姓名',
    dataIndex: 'realName'
  },
  {
    title: '角色',
    dataIndex: 'roles',
    width: 200
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 200
  }
]

const dataSource = ref([])

// 角色显示名称 - 根据角色ID和名称确定显示内容
const getRoleDisplayName = (role) => {
  // 如果是系统管理员（ID=1）
  if (role.id === 1) {
    return '系统管理员'
  }
  // 如果是普通管理员（ID=2）
  if (role.id === 2) {
    return '普通管理员'
  }
  // 其他情况显示为普通用户
  return '普通用户'
}

// 角色颜色映射
const getRoleColor = (roleId) => {
  if (roleId === 1) return 'purple'  // 系统管理员
  if (roleId === 2) return 'blue'    // 普通管理员
  if (roleId === 3) return 'green'   // 普通用户
  return 'green'  // 默认显示为普通用户颜色
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 初始化数据
const initData = async () => {
  if (!canViewPage()) {
    message.warning('您没有查询权限')
    return
  }
  
  loading.value = true
  try {
    // 先获取角色数据，用于角色标签显示
    await initRolesAndPermissions()
    
    const response = await request.get(`/users/roles`, { params: { page: current.value, size: pageSize.value } })
    if (response.data.success) {
      // 处理用户角色数据
      const processedData = processUserRoleData(response.data.data)
      originalDataSource.value = processedData
      dataSource.value = processedData
      total.value = response.data.total || processedData.length
      
      // 调试信息：打印用户角色数据
      console.log('用户角色数据:', processedData)
      if (processedData && processedData.length > 0) {
        console.log('第一个用户的角色:', processedData[0].roles)
      }
    } else {
      message.error('获取用户角色列表失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '获取用户角色列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化用户和角色数据
const initUsersAndRoles = async () => {
  try {
    const [usersResponse, rolesResponse] = await Promise.all([
      request.get('/users'),
      request.get('/roles')
    ])
    
    if (usersResponse.data.success) {
      users.value = usersResponse.data.data
    }
    if (rolesResponse.data.success) {
      roles.value = rolesResponse.data.data
    }
  } catch (error) {
    message.error('初始化数据失败')
  }
}

// 初始化角色数据（用于角色标签显示）
const initRolesAndPermissions = async () => {
  try {
    const rolesResponse = await request.get('/roles')
    if (rolesResponse.data.success) {
      roles.value = rolesResponse.data.data
    }
  } catch (error) {
    console.error('获取角色数据失败:', error)
  }
}


// 分页
const onChange = (page, pageSize) => {
  current.value = page
  pageSize.value = pageSize
  initData()
}

// 筛选选项
const filterUserOption = (input, option) => {
  const text = option.children[0].children
  return text.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

const filterRoleOption = (input, option) => {
  const text = option.children[0].children
  return text.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 模态框
const showModal = () => {
  if (!canAssign()) {
    message.warning('您没有分配角色权限')
    return
  }
  currentUser.value = null
  formState.userId = undefined
  formState.roleIds = []
  open.value = true
  initUsersAndRoles()
}

const showEditModal = (record) => {
  if (!canAssign()) {
    message.warning('您没有编辑角色权限')
    return
  }
  currentUser.value = record
  formState.userId = record.id
  formState.roleIds = record.roles ? record.roles.map(role => role.id) : []
  open.value = true
  initUsersAndRoles()
}

const resetForm = () => {
  formRef.value?.resetFields()
  currentUser.value = null
}

const handleAssignRole = () => {
  formRef.value?.validate().then(async () => {
    try {
      const assignData = {
        userId: formState.userId,
        roleIds: formState.roleIds
      }
      
      const response = await request.post('/users/roles', assignData)
      if (response.data.success) {
        message.success('角色分配成功')
        open.value = false
        resetForm()
        initData()
      } else {
        message.error(response.data.message || '分配失败')
      }
    } catch (error) {
      message.error(error.response?.data?.message || '分配失败')
    }
  }).catch(() => {
    message.error('请检查表单输入')
  })
}

// 删除用户角色
const onDeleteUserRoles = async (userId) => {
  if (!canAssign()) {
    message.warning('您没有删除角色权限')
    return
  }
  
  try {
    const response = await request.delete(`/users/${userId}/roles`)
    if (response.data.success) {
      message.success('用户角色删除成功')
      initData()
    } else {
      message.error('删除失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '删除失败')
  }
}

const goToHome = () => {
  window.location.href = '/hotel/users'
}

// 处理用户角色数据，确保角色信息正确显示
const processUserRoleData = (users) => {
  return users.map(user => {
    // 确保每个用户都有roles字段
    if (!user.roles) {
      user.roles = []
    }
    
    // 如果没有角色数据，为用户添加默认的普通用户角色
    if (user.roles.length === 0) {
      user.roles = [{
        id: 3,  // 普通用户ID
        roleName: '普通用户',
        roleCode: 'user'
      }]
    }
    
    return user
  })
}

onMounted(() => {
  initData()
})
</script>

<style scoped>
.editable-cell {
  position: relative;
}

.editable-cell-input-wrapper,
.editable-cell-text-wrapper {
  padding-right: 24px;
}

.editable-cell-text-wrapper {
  padding: 5px 24px 5px 5px;
}

.editable-cell-icon,
.editable-cell-icon-check {
  position: absolute;
  right: 0;
  width: 20px;
  cursor: pointer;
}

.editable-cell-icon {
  margin-top: 4px;
  display: none;
}

.editable-cell-icon-check {
  line-height: 28px;
}

.editable-cell-icon:hover,
.editable-cell-icon-check:hover {
  color: #108ee9;
}

.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
</style>